
function getMaxMin(slice, high, low) {
    let max = slice[0][high]
    let min = slice[0][low]
    slice.forEach(data => {
        max = Math.max(max, data[high])
        min = Math.min(min, data[low])
    })
    return [max, min]
}

const stoch = {
    name: 'HIGH_SLOPE',
    shortName: 'HIGH_SLOPE',
    calcParams: [20],
    figures: [
        { key: 'highSlope', title: 'High Slope: ', type: 'line' }
    ],
    calc: (dataList, indicator) => {
        let prevHigh = null;
        let prevLow = null;
        let lastBody = null;
        let lastVolume = null;
        let prevKD = {
            k: 1,
            d: 1
        };
        const kdjr = [];
        return dataList.map((kLineData, i) => {
            // console.log(i);
            const kdj= {}
            const close = kLineData.close
            if (i >= 9 - 1) {
                const lhn = getMaxMin(dataList.slice(i - (9 - 1), i + 1), 'high', 'low')

                const hn = lhn[0]
                const ln = lhn[1]


                const hnSubLn = hn - ln
                const rsv = (close - ln) / (hnSubLn === 0 ? 1 : hnSubLn) * 100

                kdj.k = ((3 - 1) * (kdjr[i - 1]?.k ?? 50) + rsv) / 3
                kdj.d = ((3 - 1) * (kdjr[i - 1]?.d ?? 50) + kdj.k) / 3

                if(i==100){
                    console.log("currKDHNLN", hn, ln, rsv, kdj.k, kdj.d)
                }
            } else {
                return {
                    highSlope: 0
                }
            }
            // console.log("kdj",kdj)

            const high = kLineData.high;
            const low = kLineData.low;
            const body = close - kLineData.open;
            const upperShadow = 1 - (kLineData.high - Math.max(close, kLineData.open))/body;
            const result = {};
            const volume = kLineData.volume;

            if (prevHigh != null) {
                result.highSlope = high / prevLow;
            }
            if(prevLow != null) {
                result.lowSlope = low / prevLow;
            }
            if(i==9)
                console.log("currKD2", i, kdj)
            var newkdslope = kdj.k / prevKD.k;
            var lastkdslope = kdj.d / prevKD.d;
            var direction = (kdj.k - kdj.d)>0?1:-1;
            var volSlope = volume / lastVolume;
            var kdslope = newkdslope / lastkdslope;

            // console.log("?", kdslope)
            // var upNum = (result.highSlope * kdslope * body/lastBody ) * 180 / Math.PI
            var upNum = Math.atan(result.highSlope * kdslope) * 180 / Math.PI
            result.highSlope = upNum
            if(upNum  >= 50) {
                result.highSlope = upNum
                // result.highSlope = 1
            } else{
                result.highSlope = -1
            }
            prevHigh = high;
            prevLow = low;
            prevKD = kdj;
            lastBody = body;
            lastVolume = volume;
            return result;
        });
    }
};

export default stoch;
